package com.ias.agdis_r.activity.setting;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseKeyActivity;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.netservice.actions.PrivateNetService;
import com.ias.agdis_r.netservice.actions.PublicNetService;
import com.ias.agdis_r.netservice.actions.WifiNetService;
import com.ias.agdis_r.util.S;

public class NetChooseActivity extends BaseKeyActivity {

	private Map<Integer, TextView> text_list = new LinkedHashMap<Integer, TextView>();
	private ActionBar actionBar;
	private RadioGroup r1;
	private RadioGroup r2;
	private RadioGroup r3;
	private ImageView btn_back;
	private Spinner spinner_interval;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_net_choose);
		actionBar = getActionBar();
		initActionBar();
		r1 = (RadioGroup) findViewById(R.id.pub_group);
		r2 = (RadioGroup) findViewById(R.id.pri_group);
		r3 = (RadioGroup) findViewById(R.id.wifi_group);
		btn_back = (ImageView)findViewById(R.id.actionbar_settings_back);
		spinner_interval = (Spinner) findViewById(R.id.spinner_interval);
		r1.setOnCheckedChangeListener(check_change_listener);
		r2.setOnCheckedChangeListener(check_change_listener);
		r3.setOnCheckedChangeListener(check_change_listener);
		
		Integer[] spinner_array = new Integer[19];
		for(int i=0;i<spinner_array.length;i++)
		{
			spinner_array[i] = i+2;
		}
		ArrayAdapter<Integer> spinner_adapter = new ArrayAdapter<Integer>(NetChooseActivity.this, R.layout.flight_spinner1_item,
				spinner_array);
		
		spinner_interval.setAdapter(spinner_adapter);
		
		btn_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				checkData();
			}
		});
		
		loadData();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode == KeyEvent.KEYCODE_BACK) 
		{
			checkData();
		}
		return false;
	}
	
	/**
	 * 校验输入数据
	 */
	private void checkData()
	{
		if(saveData())
		{
			finish();
		}
	}
	
	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
	}
	
	/**
	 * 加载内容
	 */
	private void loadData()
	{
		int sec = DataBaseManager.getInstance().getInt(ParameterModel.INTERVAL, ParameterModel.INTERVAL);
		if(sec-2>=0)
		{
			spinner_interval.setSelection(sec-2);
		}
		
		String netList = DataBaseManager.getInstance().getString(ParameterModel.T_NET_SELECT_INFO,
				ParameterModel.NET_LIST);
		String[] strs = netList.split(",");
		for (String str : strs) {
			if (ParameterModel.PUBLIC_TAB_NUM.equals(str)) {
				((RadioButton) r1.getChildAt(2)).setChecked(true);
			} else if (ParameterModel.PRIVATE_TAB_NUM.equals(str)) {
				((RadioButton) r2.getChildAt(2)).setChecked(true);
			} else if (ParameterModel.WIFI_TAB_NUM.equals(str)) {
				((RadioButton) r3.getChildAt(2)).setChecked(true);
			}
		}
	}
		
	/**
	 * 保存数据
	 */
	private boolean saveData()
	{
		int sec = spinner_interval.getSelectedItemPosition()+2;
		WifiManager wifiManager = (WifiManager) DataBaseManager.getInstance().getContext().getApplicationContext()
				.getSystemService(Context.WIFI_SERVICE);
		Set<Integer> set = text_list.keySet();
		StringBuffer sbf = new StringBuffer();
		boolean openWifi = false;
		for (Integer it : set) {
			String ip_restful;
			String port_restful;
			String ip_push;
			String port_push;
			if (r1.getId() == it) {
				ip_restful = DataBaseManager.getInstance().getString(ParameterModel.T_PUBLIC_INFO,
						ParameterModel.NET_IP_RESTFUL);
				port_restful = DataBaseManager.getInstance().getString(ParameterModel.T_PUBLIC_INFO,
						ParameterModel.NET_PORT_RESTFUL);
				ip_push = DataBaseManager.getInstance().getString(ParameterModel.T_PUBLIC_INFO,
						ParameterModel.NET_IP_PUSH);
				port_push = DataBaseManager.getInstance().getString(ParameterModel.T_PUBLIC_INFO,
						ParameterModel.NET_PORT_PUSH);
				if (S.isEmpty(ip_restful)||S.isEmpty(ip_push)||S.isEmpty(port_push)||S.isEmpty(port_restful)) {
					EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE,getString(R.string.unconfig_public), false);
					startIPSetting(PublicNetService.class.getName());
					return false;
				}
				sbf.append(ParameterModel.PUBLIC_TAB_NUM).append(",");
			} else if (r2.getId() == it) {
				ip_restful = DataBaseManager.getInstance().getString(ParameterModel.T_PRIVATE_INFO,
						ParameterModel.NET_IP_RESTFUL);
				port_restful = DataBaseManager.getInstance().getString(ParameterModel.T_PRIVATE_INFO,
						ParameterModel.NET_PORT_RESTFUL);
				ip_push = DataBaseManager.getInstance().getString(ParameterModel.T_PRIVATE_INFO,
						ParameterModel.NET_IP_PUSH);
				port_push = DataBaseManager.getInstance().getString(ParameterModel.T_PRIVATE_INFO,
						ParameterModel.NET_PORT_PUSH);
				if (S.isEmpty(ip_restful)||S.isEmpty(ip_push)||S.isEmpty(port_push)||S.isEmpty(port_restful)) {
					EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE,getString(R.string.unconfig_private), false);
					startIPSetting(PrivateNetService.class.getName());
					return false;
				}
				sbf.append(ParameterModel.PRIVATE_TAB_NUM).append(",");
			} else if (r3.getId() == it) {

				String ssid = "";
				ssid = DataBaseManager.getInstance().getString(ParameterModel.T_WIFI_INFO,
						ParameterModel.NET_SSID);
				ip_restful = DataBaseManager.getInstance().getString(ParameterModel.T_WIFI_INFO,
						ParameterModel.NET_IP_RESTFUL);
				port_restful = DataBaseManager.getInstance().getString(ParameterModel.T_WIFI_INFO,
						ParameterModel.NET_PORT_RESTFUL);
				ip_push = DataBaseManager.getInstance().getString(ParameterModel.T_WIFI_INFO,
						ParameterModel.NET_IP_PUSH);
				port_push = DataBaseManager.getInstance().getString(ParameterModel.T_WIFI_INFO,
						ParameterModel.NET_PORT_PUSH);
				if (S.isEmpty(ssid)||S.isEmpty(ip_restful)||S.isEmpty(ip_push)||S.isEmpty(port_push)||S.isEmpty(port_restful)) {
					EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE,getString(R.string.unconfig_wifi), false);
					startIPSetting(WifiNetService.class.getName());
					return false;
				}
				sbf.append(ParameterModel.WIFI_TAB_NUM).append(",");
				openWifi = true;
			}
			
			if(openWifi)
			{
				if(!wifiManager.isWifiEnabled())
				{
					wifiManager.setWifiEnabled(true);
				}
			}
			else
			{
				if(wifiManager.isWifiEnabled())
				{
					wifiManager.setWifiEnabled(false);
				}
			}
			
		}

		DataBaseManager.getInstance().insert(ParameterModel.INTERVAL, ParameterModel.INTERVAL, sec);// 保存检查网络的时间间隔

		if (sbf.length() > 0)
			sbf.deleteCharAt(sbf.length() - 1);
		if (DataBaseManager.getInstance().insert(ParameterModel.T_NET_SELECT_INFO,
				ParameterModel.NET_LIST, sbf.toString())) {
		}
		
		EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, getString(R.string.saveNetChoose), false);
		return true;
	}
	
	@SuppressLint("InflateParams")
	private void initActionBar() {
		actionBar.setCustomView(LayoutInflater.from(NetChooseActivity.this)
				.inflate(R.layout.actionbar_settings, null));
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);
		TextView title = (TextView) findViewById(R.id.txt_title);
		title.setText(R.string.NetChooseActivity);
	}
	

	private RadioGroup.OnCheckedChangeListener check_change_listener = new RadioGroup.OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(RadioGroup r, int arg1) {
			LinearLayout l = (LinearLayout) findViewById(R.id.net_order);
			TextView tv = text_list.get(r.getId());
			RadioButton rb = ((RadioButton) r.getChildAt(2));
			if (arg1 == rb.getId()) {
				showUseNet(r);
			} else {
				text_list.remove(r.getId());
				l.removeView(tv);
			}
		}
	};
	
	private void showUseNet(RadioGroup r) {
		TextView name_tv = (TextView) r.getChildAt(0);
		LinearLayout l = (LinearLayout) findViewById(R.id.net_order);
		TextView tv = new TextView(this);
	
		tv.setTextSize(20);
		tv.setTextColor(Color.BLACK);
		tv.setGravity(Gravity.CENTER);

		//根据分辨率设置LayoutParams的宽度 add by zsc
		int textSize=(int)tv.getTextSize();
		int paramsSize=textSize*40/15;
		LayoutParams lp = new LayoutParams(paramsSize, LayoutParams.WRAP_CONTENT);
		
		tv.setLayoutParams(lp);

		String name = name_tv.getText().toString();
		tv.setText(name.substring(0, name.indexOf(":")));
		l.addView(tv);
		text_list.put(r.getId(), tv);
	}
	
	private void startIPSetting(String type)
	{
		Intent intent = new Intent(this, IPSettingActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("type", type);
		startActivity(intent);
	}
}
